package com.ship.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.enums.MessageTypeEnum;
import com.ship.common.core.enums.NotifyType;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.system.api.domain.SysMessageSend;
import com.ship.system.api.domain.SysUser;
import com.ship.system.buesiness.MoveCloudBusiness;
import com.ship.system.domain.SysMessage;
import com.ship.system.domain.SysMessageConfig;
import com.ship.system.service.ISysUserService;
import com.ship.system.service.SysMessageConfigService;
import com.ship.system.service.SysMessageService;
import com.ship.system.mapper.SysMessageMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author zhangyh
* @description 针对表【sys_message(系统消息信息表)】的数据库操作Service实现
* @createDate 2024-03-27 09:26:04
*/
@Service
public class SysMessageServiceImpl extends BaseServiceImpl<SysMessageMapper, SysMessage>
    implements SysMessageService{

    private static final Logger logger = LoggerFactory.getLogger(SysMessageServiceImpl.class);

    @Autowired
    private SysMessageConfigService sysMessageConfigService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private MoveCloudBusiness moveCloudBusiness;

    @Override
    public JsonResult<SysMessage> getDetail(Long messageId) {
        SysMessage sysMessage = this.baseMapper.selectById(messageId);
        if(sysMessage == null){
            return JsonResult.failed("消息信息异常！");
        }

        if(sysMessage.getMessageStatus() != null && 1 == sysMessage.getMessageStatus() && 0 == sysMessage.getReadStatus()){
            sysMessage.setReadStatus(1);
            this.baseMapper.updateById(sysMessage);
        }

        return JsonResult.success(sysMessage);
    }

    @Override
    public JsonResult finishTask(Long messageId) {
        SysMessage sysMessage = this.baseMapper.selectById(messageId);
        if(sysMessage == null){
            return JsonResult.failed("消息信息异常！");
        }
        if(sysMessage.getFinishStatus() != null && 1 == sysMessage.getFinishStatus()){
            sysMessage.setFinishStatus(0);
            sysMessage.setReadStatus(0);
        }else{
            sysMessage.setFinishStatus(1);
            sysMessage.setReadStatus(1);
        }
        this.baseMapper.updateById(sysMessage);
        return JsonResult.success();
    }

    @Override
    public void saveMessage(SysMessageSend messageSend) {
        //获取配置信息
        SysMessageConfig messageConfig = sysMessageConfigService.getById(messageSend.getMessageType());
        if(messageConfig == null){
            return;
        }

        if(0 == messageConfig.getMessageStatus()){
            //禁用
            return;
        }

        if(messageConfig.getConditionType() != 1 && messageSend.getCompareValue() != null){
            //触发条件判断，比较基准值

            Boolean checkValue = false;
            if(messageSend.getCompareType() == 1){
                checkValue = messageSend.getCompareValue() > messageConfig.getConditionValue();
            }else if(messageSend.getCompareType() == 2){
                checkValue = messageSend.getCompareValue() >= messageConfig.getConditionValue();
            }else if(messageSend.getCompareType() == 3){
                checkValue = messageSend.getCompareValue() < messageConfig.getConditionValue();
            }else if(messageSend.getCompareType() == 4){
                checkValue = messageSend.getCompareValue() <= messageConfig.getConditionValue();
            }else{
                checkValue = messageSend.getCompareValue() == messageConfig.getConditionValue();
            }
            if(!checkValue){
                return;
            }
        }

        List<Long> sendUid = new LinkedList<>();

        if(messageSend.getOtherUsernameList() != null && messageSend.getOtherUsernameList().size() > 0){
            List<SysUser> userList = sysUserService.listByUserNames(messageSend.getOtherUsernameList());
            if(userList.size() > 0){
                sendUid.addAll(userList.stream().map(SysUser::getUserId).collect(Collectors.toList()));
            }
        }

        if(StringUtils.isNotBlank(messageConfig.getNoticeUids())){
            sendUid.addAll(
                    Arrays.stream(messageConfig.getNoticeUids().split(","))
                    .map(Long::valueOf)
                    .collect(Collectors.toList())
            );
        }
        if(sendUid.size() == 0){
            return;
        }
        String messageContent = messageConfig.getContentTemplate();
        String[] params = messageSend.getContentParam();
        if(params != null){
            for (int i = 0; i < params.length; i++) {
                messageContent = messageContent.replace("#" + i + "#", params[i]);
            }
        }
        List<SysUser> userList = sysUserService.listByIds(sendUid);

        List<SysMessage> saveMessageList = new LinkedList<>();
        for (SysUser sysUser : userList) {
            SysMessage sysMessage = new SysMessage();
            sysMessage.setMessageTitle(messageConfig.getConfigTitle());
            sysMessage.setMessageContent(messageContent);
            sysMessage.setMessageUrl(messageSend.getMessageUrl());
            sysMessage.setMessageStatus(messageConfig.getMessageStatus());
            sysMessage.setTaskStatus(messageConfig.getTaskStatus());
            sysMessage.setModuleType(Integer.parseInt(messageConfig.getNoticeModule()));
            sysMessage.setNoticeTime(new Date());
            sysMessage.setCreateDate(new Date());
            sysMessage.setCreateBy(SecurityUtils.getUsername());
            sysMessage.setNoticeUid(sysUser.getUserId());
            saveMessageList.add(sysMessage);
        }
        if(saveMessageList.size() > 0){
            this.saveBatch(saveMessageList);
        }
        if(1 == messageConfig.getThirdPushStatus() && userList.size() > 0){
            //开启移动云，调用移动云推送API
            String messageUrl = messageSend.getMessageUrl();
            String userNames = userList.stream().map(SysUser::getUserName).collect(Collectors.joining(","));
            String userMail = userList.stream().map(SysUser::getEmail).collect(Collectors.joining(","));
            try {
                logger.info("移动云消息发送参数："+userNames+" ----- "+messageUrl);
                moveCloudBusiness.sendMoveCloudMessage(NotifyType.MESSAGE,userNames,messageContent,"");
//                if(StringUtils.isNotBlank(messageUrl)){
//                    MoveCloudBusiness.sendMoveCloudMessage(NotifyType.LINK,userNames,messageContent,messageUrl);
//                }else{
//                    MoveCloudBusiness.sendMoveCloudMessage(NotifyType.MESSAGE,userNames,messageContent,"");
//                }
                sendMail(userMail,messageContent,messageConfig.getConfigTitle());
            }catch (Exception e){
                e.printStackTrace();
                logger.error("移动云消息发送异常："+e.getMessage());
            }
        }
    }

    @Override
    public JsonResult getUnreadCount() {
        Long count = this.baseMapper.selectCount(
                new LambdaQueryWrapper<SysMessage>()
                .eq(SysMessage::getNoticeUid,SecurityUtils.getUserId())
                .eq(SysMessage::getMessageStatus,1)
                .eq(SysMessage::getReadStatus,0)
        );
        return JsonResult.success(count);
    }

    @Override
    public JsonResult exchangeTask(Long messageId) {
        SysMessage sysMessage = this.baseMapper.selectById(messageId);
        if(sysMessage == null){
            return JsonResult.failed("消息信息异常！");
        }
        sysMessage.setMessageStatus(0);
        sysMessage.setTaskStatus(1);
        sysMessage.setReadStatus(0);
        sysMessage.setFinishStatus(0);
        this.baseMapper.updateById(sysMessage);
        return JsonResult.success();
    }

    public void sendMail(String toAdd,String content,String total){
        // 发件人电子邮件地址
        String from = "sy_cbdd@cnooc.com.cn";

        // SMTP服务器地址
        String host = "cmail.cnooc.com.cn";

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", "25"); // 或者465，取决于你的SMTP服务器配置
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true"); // 如果使用TLS

        // 获取默认的Session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, "W!injrt9nv2kdea");
            }
        });

        try {
            // 创建默认的MimeMessage对象
            MimeMessage message = new MimeMessage(session);

            // 设置发件人
            message.setFrom(new InternetAddress(from));

            // 设置收件人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAdd));

            // 设置 Subject: 头部字段
            message.setSubject(total);

            // 现在设置实际消息
            message.setText(content);

            // 发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            System.out.println(mex.getMessage());
            mex.printStackTrace();
        }
    }
}




